// ============================== 导入依赖 ============================== //

const client = require('scp2')
const ora = require('ora')
const chalk = require('chalk')

const DEV = {
  host: '192.168.139.101',
  username: 'cssdev',
  password: 'HTgx_2021',
  path: '/data/wisestone/ws-rely-nginx',
}

// ============================== 导出部署 ============================== //

module.exports = async (folder) => {
  deploy(folder, DEV, '开发环境')
}

// ============================== 内部方法 ============================== //

const begin = Date.now()

const tip = (folder, type = '') => {
  const time = new Date().toString().replace(/.*(\d\d:\d\d:\d\d).*/, '$1')
  const seconds = ((Date.now() - begin) / 1000).toFixed(1)
  return `【${time}】 ${folder} 【用时 ${seconds} 秒】：${type} `
}

const deploy = (folder, SERVER, type) => {
  const spinner = ora(chalk.cyan(tip(folder))).start()

  const timer = setInterval(() => {
    spinner.text = chalk.cyan(`${tip(folder)}部署中...`)
  }, 100)

  const config = { ...SERVER, path: `${SERVER.path}${folder}` }

  return new Promise((resolve) => {
    client.scp(`dist${folder}`, config, (err) => {
      clearInterval(timer)
      if (err) spinner.fail(chalk.red(`${tip(folder, type)}部署失败`))
      else spinner.succeed(chalk.green(`${tip(folder, type)}部署成功`))
      resolve()
    })
  })
}
